;(function($, window, document,undefined) {
    //定义的构造函数
    var ZTreeSelect = function(ele, opt) {
        this.ele = ele;
        this.renderId = opt.renderId;
        this.name = opt.name;
        this.url = opt.url;
        this.params = opt.params;
        this.callback = opt.callback;
    }
    //定义方法
    ZTreeSelect.prototype = {
        init: function() {
            var self = this;
            $(this.ele).append(
                '<input type="text" readonly="readonly" placeholder="请选择" class="btn-default dropdown-toggle form-control"  id="' + this.name + '_name" />'+
                '<span style="float: right;margin-top: -16px;margin-right: 5px;" class="caret"></span>'+
                '<input type="text" hidden id="' + this.name + '" name="' + this.name + '"/> '+
                '<div id="ztreeContent"  class="ztreeContent " ' +
                'style="height:150px;overflow-y:auto;background-color: #fff;background-clip: padding-box;' +
                'border: 1px solid rgba(0,0,0,.15);border-radius: 4px;box-shadow: 0 6px 12px rgba(0,0,0,.175);display: none;">' +
                '<input  type="text" class="form-control"  placeholder="搜索"  id="key" name="key" maxlength="50" />' +
                '<ul id="zTreeSelectTree" class="ztree" style="margin-top:0; width:100%; height:auto;"></ul>' +
                '</div>'
            );
            var setting = {
                async: {
                    enable: true,
                    type: "POST",
                    dataType: "json",
                    url: this.url,
                    autoParam: ["id"],
                    otherParam: this.params
                },
                check: {
                    enable: true,
                    chkStyle: "radio",
                    radioType: "all"
                },
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onAsyncSuccess: this.zTreeOnAsyncSuccess,//异步加载成功的fun
                    onAsyncError: this.zTreeOnAsyncError, //加载错误的fun
                    onClick: this.onClickNode,
                    onCheck: function(e, treeId, treeNode) {
                        var zTree = $.fn.zTree.getZTreeObj(treeId),
                            nodes = zTree.getCheckedNodes(true),
                            v = "";
                        var parentid = "";
                        for (var i = 0, l = nodes.length; i < l; i++) {
                            v += nodes[i].name + ",";
                            parentid += nodes[i].id + ",";
                        }
                        if (v.length > 0) {
                            v = v.substring(0, v.length - 1);
                            parentid = parentid.substring(0, parentid.length - 1);
                        }
                        else {
                            return;
                        }
                        $("#" + self.name+'_name').val(v);
                        $("#" + self.name).val(parentid);
                        self.callback(parentid, treeNode);
                        self.hideNodes();
                    } ,
                    beforeExpand: this.zTreeBeforeExpand
                }

            };
            var tree = $.fn.zTree.init($("#zTreeSelectTree"), setting);

            var key = $("#key");
            key.bind("focus", this.focusKey).bind("blur", {tree: tree}, function(e) {
                var key = $(e.currentTarget);
                if (key.get(0).value === "") {
                    key.addClass("empty");
                }
                self.searchNode(key, e.data.tree);
            }).bind("change cut input propertychange", this.searchNode(key, tree));
            key.bind('keyup', function (e) {
                self.searchNode(key, tree);
            });
        
            $('#'+ this.name+'_name').click(function () {
                self.showdivNodes();
            });

            var id = $(this.ele).data('id');
            var name = $(this.ele).data('name');
            if(id && name){
                $("#" + this.name+'_name').val(name);
                $("#" + this.name).val(id);
            }
        } ,
        showdivNodes : function() {
            // var y = parseFloat($('#' + this.renderId).offset().top) + parseFloat($('#' + this.renderId).css("height"));
            // var x = $('#' + this.inputObjId).offset().left;
            // console.log($('#' + this.inputObjId));
            $("#ztreeContent").css({
                position: 'absolute',
                width: $('#' + this.renderId).css("width"),
                zIndex: '900',
                // left: x,
                // top: y
            }).slideDown("fast");
            $("body").bind("mousedown", this.onBodyDown);
        } ,
        hideNodes : function() {
            $("#ztreeContent").css({display:'none'}).fadeOut("fast");
            $("body").unbind("mousedown", this.onBodyDown);
        } ,
        onBodyDown : function(event) {
            if (!(event.target.id == "ztreeContent" || event.target.id == this.inputObjId || $(event.target).parents("#ztreeContent").length > 0)) {
                $("#ztreeContent").css({display:'none'}).fadeOut("fast");
                $("body").unbind("mousedown", this);
            }
        } ,
        onClickNode : function(e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            zTree.checkNode(treeNode, !treeNode.checked, null, true);
            return false;
        } ,
        focusKey : function(e) {
            var key = $(e.currentTarget);
            if (key.hasClass("empty")) {
                key.removeClass("empty");
            }
        } ,
        searchNode : function(key, tree) {
            // 取得输入的关键字的值
            var value = $.trim($(key).val());
            // 按名字查询
            var keyType = "name";
            if (key.hasClass("empty")) {
                value = "";
            }

            // 如果和上次一次，就退出不查了。

            if (this.lastValue === value) {
            }

            // 保存最后一次
            this.lastValue = value;
            var nodes = tree.getNodes();
            // 如果要查空字串，就退出不查了。


            this.hideAllNode(tree, nodes);
            var nodeList = tree.getNodesByParamFuzzy(keyType, value);
            this.updateNodes(tree, nodeList);
        } ,
        showAllNode : function(tree, nodes) {
            nodes = tree.transformToArray(nodes);
            for (var i = nodes.length - 1; i >= 0; i--) {

                if (nodes[i].getParentNode() != null) {
                    tree.expandNode(nodes[i], false, false, false, false);
                } else {
                    tree.expandNode(nodes[i], true, true, false, false);
                }
                tree.showNode(nodes[i]);
                this.showAllNode(tree, nodes[i].children);

            }
        } ,
        hideAllNode : function(tree, nodes) {
            nodes = tree.transformToArray(nodes);
            for (var i = nodes.length - 1; i >= 0; i--) {
                tree.hideNode(nodes[i]);
            }
        } ,
        updateNodes : function(tree, nodeList) {
            tree.showNodes(nodeList);
            for (var i = 0, l = nodeList.length; i < l; i++) {

                //展开当前节点的父节点
                tree.showNode(nodeList[i].getParentNode());
                //显示展开符合条件节点的父节点
                while (nodeList[i].getParentNode() != null) {
                    tree.expandNode(nodeList[i].getParentNode(), true, false, false);
                    nodeList[i] = nodeList[i].getParentNode();
                    tree.showNode(nodeList[i].getParentNode());
                }
                //显示根节点
                tree.showNode(nodeList[i].getParentNode());
                //展开根节点
                tree.expandNode(nodeList[i].getParentNode(), true, false, false);
            }
        } ,
        zTreeBeforeExpand : function(treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            treeObj.reAsyncChildNodes(treeNode, "refresh");
        } ,
        zTreeOnAsyncError : function(event, treeId, treeNode) {
        } ,
        zTreeOnAsyncSuccess : function(event, treeId, treeNode, msg) {
        }
    }

    //插件
    $.fn.ztreeSelect = function(options) {
        //创建实体
        var ztreeSelect = new ZTreeSelect(this, options);
        //调用方法
        ztreeSelect.init();
        return this;
    }
})(jQuery, window, document);